﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace SharedFileDownload.Core
{
	public class FileShared
	{
		/// <summary>
		/// 连接远程共享文件夹
		/// </summary>
		/// <param name="path">远程共享文件夹的路径</param>
		/// <param name="userName">用户名</param>
		/// <param name="passWord">密码</param>
		/// <returns></returns>
		public static bool connectState(string path, string userName, string passWord)
		{
			bool Flag = false;
			Process proc = new Process();
			try
			{
				proc.StartInfo.FileName = "cmd.exe";
				proc.StartInfo.UseShellExecute = false;
				proc.StartInfo.RedirectStandardInput = true;
				proc.StartInfo.RedirectStandardOutput = true;
				proc.StartInfo.RedirectStandardError = true;
				proc.StartInfo.CreateNoWindow = true;
				proc.Start();
				string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
				proc.StandardInput.WriteLine(dosLine);
				proc.StandardInput.WriteLine("exit");
				while (!proc.HasExited)
				{
					proc.WaitForExit(1000);
				}
				string errormsg = proc.StandardError.ReadToEnd();
				proc.StandardError.Close();
				if (string.IsNullOrEmpty(errormsg))
				{
					Flag = true;
				}
				else
				{
					throw new Exception(errormsg);
				}
			}
			catch (Exception ex)
			{
				throw ex;
			}
			finally
			{
				proc.Close();
				proc.Dispose();
			}
			return Flag;
		}
		/// <summary>
		/// 获取共享目录项
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		public static DirectoryInfo ConnectShareDireInfo(string path)
		{
			return new DirectoryInfo(path);
		}
	}
}
